/**
 * Created by htzhanglong on 2015/8/2.
 */
angular.module('starter.controllers', [])

    .controller('todoCtrl', function($scope,$rootScope,ENV,TodoRepairOrderList,$ionicHistory,queryNum) {
        $scope.showloading=true;
        $scope.ENV=ENV;
        // 获取第一页数据
        TodoRepairOrderList.getTopOrders();


        $scope.$on('TodoOrderList.portalsUpdated', function() {

            queryNum.query();
            // $timeout(function() {
            $scope.orderListData = TodoRepairOrderList.getOrders();
            $scope.showloading=false;

            // }, 100);
        });

        $scope.doRefresh = function() {
            // queryNum.getTodoNum();
            TodoRepairOrderList.getTopOrders();
            $scope.$broadcast('scroll.refreshComplete');
        };

        $scope.loadMore = function() {
            console.log("loadMore");
            TodoRepairOrderList.getMoreOrders();
            $scope.$broadcast('scroll.infiniteScrollComplete');

        };
        $scope.moreDataCanBeLoaded = function() {
            //console.log(PortalsFactory.hasNextPage());
            return TodoRepairOrderList.hasNextPage();
        };
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        //

    })
    //报修详情
    .controller('detailCtrl', function($scope,$rootScope,ENV,$ionicModal,$state,$stateParams,$ionicPopover,$ionicActionSheet,RepairOrderContent,$ionicLoading,$ionicHistory,$timeout,webview) {
        $scope.ENV=ENV.api.slice(0,ENV.api.length-1);
        $scope.showloading=true;
        $scope.img=[];
        // $scope.img.src="img/ionic.png";

        var aid=$stateParams.aid;
        RepairOrderContent.get(aid);

        $scope.doRefresh = function() {
          RepairOrderContent.get(aid);
          $scope.$broadcast('scroll.refreshComplete');
        };


      $scope.$on('RepairOrder.contentUpdated', function() {

            // $timeout(function() {
            $scope.orderDetail = RepairOrderContent.getArticle();
            $scope.img=$scope.orderDetail.rapairPicUrls.split(",");
            $scope.showloading=false;

            // }, 100);
        });

        //显示打电话actionsheet
        $scope.showSheet = function(data) {
            // 显示操作表
            console.log("电话"+data);
            $ionicActionSheet.show({
                buttons: [
                    { text: data },
                ],
                // destructiveText: 'Delete',
                cancelText: '取消',
                buttonClicked: function(index) {
                   console.log('dianji:'+data);
                    phonedialer.dial(data, function(err) {
                        if (err == "feature")
                            alert("Your device doesn't support this feature.");
                        if (err == "empty")
                            alert("Unknown phone number");
                    });
                }
            });

        };

        $scope.grab=function (id) {
            console.log("id"+id);
            RepairOrderContent.grab(id);
        };

        $scope.$on('RepairOrder.grabSuccess', function() {
            $scope.grabResult = RepairOrderContent.getGrabResult();
            console.log("grabResult"+$scope.grabResult);
            $ionicLoading.show({
                noBackdrop: true,
                template: $scope.grabResult.msg,
                duration: 1500
            });

            $timeout(function(){
                // $ionicHistory.goBack();
                $state.go("tab.todo",{},{reload:true});
            },1500);
        });

        //返回
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        $ionicModal.fromTemplateUrl('modal.html', function (modal) {
          $scope.modal = modal;
        }, {
          animation: 'slide-in-left',
          focusFirstInput: true
        });

        $scope.showBigPic=function(src){
          $scope.modal.src=src;
          console.log(src);
          $scope.modal.show();

        }
        $scope.openWeb=function(param){
          webview.openWeb(param);
        }

    })
    //跟进详情
    .controller('followDetailCtrl', function($scope,$rootScope,ENV,TurnTransfor,$ionicPopup,startRepair,RepairNode,$ionicModal,$stateParams,$ionicPopover,$ionicActionSheet,$ionicHistory,RepairOrderContent,TurnException,$state,Toast) {
        $scope.url=ENV.api.substring(0,ENV.api.length-1);
        $scope.showloading=true;
        $scope.orderDetail={};
        $scope.aid=$stateParams.aid;
        $scope.orderId=$stateParams.orderId;
        $scope.img=[];
        $scope.turnContent='';      //上报理由
        // $scope.message.report='';

        // console.log("id是："+aid+"$scope.orderDetail:"+$scope.orderDetail);
        RepairOrderContent.get($scope.aid); //获取订单详情
        RepairNode.getRepairNodes($scope.orderId);
        $scope.$on('RepairOrder.contentUpdated', function() {

            $scope.orderDetail = RepairOrderContent.getArticle();
            $scope.img=$scope.orderDetail.rapairPicUrls.split(",");

            $scope.showloading=false;
        });

        $scope.$on('RepairOrder.nodeSuccessEd', function() {

          $scope.repairNodes= RepairNode.getNodes();

        });


        $scope.doRefresh = function() {
            RepairOrderContent.get($scope.aid);
            RepairNode.getRepairNodes($scope.orderId);
            $scope.$broadcast('scroll.refreshComplete');
        };


        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

        $ionicPopover.fromTemplateUrl("ez-popover.html", {
            scope: $scope
        })
        .then(function(popover){
            $scope.popover = popover;
        });
        $scope.openPopover = function($event) {

            $scope.popover.show($event);
        };
        $scope.closePopover = function() {
            $scope.popover.hide();

        };
        //销毁事件回调处理：清理popover对象
        $scope.$on("$destroy", function() {
            $scope.popover.remove();
        });
        // 隐藏事件回调处理
        $scope.$on("popover.hidden", function() {
            // Execute action
        });
        //删除事件回调处理
        $scope.$on("popover.removed", function() {
            // Execute action
        });

        //显示打电话actionsheet
        $scope.show = function(tel) {
            // 显示操作表
            console.log("电话"+tel);
            $ionicActionSheet.show({
                buttons: [
                    { text: tel },
                ],
                // destructiveText: 'Delete',
                cancelText: '取消',
                buttonClicked: function(index) {
                    return true;
                }
            });

        };



        $scope.grab=function (id) {
            console.log("id"+id);
        }
        //弹出转单确认框
        $scope.showConfirm = function() {
            $ionicPopup.confirm({
                title: "转单申请",
                template: "确定转单吗？",
                okText:"确定",
                cancelText:"取消"
            })
            .then(function(res) {
                console.log("确认框的结果为："+res);
                if(res) {
                    // $scope.status = "凭什么吃我的冰淇淋！";
                    TurnTransfor.putTransfor($scope.aid,'');
                    $scope.popover.hide();
                } else {
                    // $scope.status = "谢谢你不吃之恩！";
                    $scope.popover.hide();
                }
            });
        };

        //弹出警告框
        $scope.showAlert = function(msg) {
            $ionicPopup.alert({
                title: "提示",
			    template:msg
            })
            .then(function(res) {
                // $scope.status = "感谢上帝";
            });
        };


        $scope.report = function() {
            //弹出上报和转单的确认框
          $scope.message={};
          $ionicPopup.show({
              template: "<input type='text' ng-model='message.report'>",
              title: "请输入上报理由",
              // subTitle: "密码为8位",
              scope: $scope,
              buttons: [
                {text: "取消"},
                {
                  text: "<b>提交</b>",
                  type: "button-positive",
                  onTap: function (e) {
                     return $scope.message.report;
                  }
                }
              ]
            })
            .then(function (res) {
              //发送提交申请
              console.log(res);
              if(res==''||res==undefined){
                  $scope.showAlert("必须填写理由才能提交哦");
              }
              else{
                TurnException.putException($scope.aid,res);
              }
              // $scope.turnContent=res;
            });
        }

        //上报成功后，返回
        $scope.$on('RepairOrder.ExceptionEd', function() {
          $state.go("tab.task");
        });
        $scope.$on('RepairOrder.PutTurnEd', function() {
          $state.go("tab.task");
        });
        //监听到结束
        $scope.$on('RepairOrder.Finished', function() {
          $state.go("tab.task");
        });


      $ionicModal.fromTemplateUrl('modal_follw.html', function (modal) {
        $scope.modal = modal;
      }, {
        animation: 'slide-in-left',
        focusFirstInput: true
      });
      $scope.showBigPic=function(src){
        //点击开始维修
        $scope.modal.src=src;
        console.log(src);

        $scope.modal.show();
      }
      $scope.startRepair=function(id){
        startRepair.start(id);
      }

      $scope.$on('StartRepair.Started', function() {
        $state.go("tab.task");
      });

      //显示打电话actionsheet
      $scope.showSheet = function(data) {
        // 显示操作表
        console.log("电话"+data);
        $ionicActionSheet.show({
          buttons: [
            { text: data },
          ],
          // destructiveText: 'Delete',
          cancelText: '取消',
          buttonClicked: function(index) {
            console.log('dianji:'+data);
              //IOS 打电话
              phonedialer.dial(data, function(err) {
                  if (err == "feature")
                      alert("Your device doesn't support this feature.");
                  if (err == "empty")
                      alert("Unknown phone number");
              });
          }
        });

      };


      //点击结束
      //弹出转单确认框
        $scope.finishConfirm = function() {
          $ionicPopup.confirm({
            title: "结束维修",
            template: "确定结束吗？",
            okText:"确定",
            cancelText:"取消"
          })
            .then(function(res) {
              if(res) {
                TurnTransfor.finishOrder($scope.aid);
                $scope.popover.hide();
              } else {
                // $scope.status = "谢谢你不吃之恩！";
                $scope.popover.hide();
              }
            });
        };

    })
    .controller('knowledgeCtrl', function($scope,$rootScope,ENV,$ionicHistory) {


        // $scope.back = function(){
        //     $ionicHistory.goBack();
        //     console.log("back");
        // };
        $scope.openWeb=function() {
          cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php?do=search&id=%E5%93%88%E5%93%88%E5%93%88', '_blank', {
              statusbar: {
                  color: '#444444'
              },
              toolbar: {
                  height: 44,
                  color: '#444444'
              },
              title: {
                  color: '#ffffff',
                  staticText: '知识库',
                  showPageTitle: false
              },
              backButton: {
                  wwwImage: 'img/back.png',
                  wwwImagePressed: 'back_pressed',
                  align: 'left',
                  event: 'backPressed'
              },
            //customButtons: [
            //  {
            //    image: 'share',
            //    imagePressed: 'share_pressed',
            //    align: 'right',
            //    event: 'sharePressed'
            //  }
            //],
            //menu: {
            //  image: 'menu',
            //  imagePressed: 'menu_pressed',
            //  title: 'Test',
            //  cancel: 'Cancel',
            //  align: 'right',
            //  items: [
            //    {
            //      event: 'helloPressed',
            //      label: 'Hello World!'
            //    },
            //    {
            //      event: 'testPressed',
            //      label: 'Test!'
            //    }
            //  ]
            //},
            backButtonCanClose: true
          }).addEventListener('backPressed', function (e) {
            // alert('back pressed');
          }).addEventListener('helloPressed', function (e) {
            alert('hello pressed');
          }).addEventListener('sharePressed', function (e) {
            alert(e.url);
          }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
            console.error(e.message);
          }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
            console.log(e.message);
          });
        }

      $scope.openWeb();

    })


    .controller('taskCtrl', function($scope,$rootScope,TaskList,$ionicHistory) {
        // $scope.showloading=true;
        $scope.status=0;
        $scope.changeTab = function(status,index) {
            $scope.status=status;
            var a=document.getElementById('sub_header_list').getElementsByTagName('a');
            for (var i = 0; i < 3; i++) {
                a[i].className = "button button-clear ";
            }
            a[index].className = "button button-clear sub_button_select";
            console.log("status的值："+TaskList.getCurrentStatus());
            TaskList.setOrderStatus(status,0);

        };
        TaskList.setOrderStatus(0,0);//获取第一页数据

        $scope.$on('TaskList.listUpdated', function() {

            console.log("检测到更新完毕");
            $scope.taskListData = TaskList.getList();
            console.log("$scope.taskListData:"+$scope.taskListData);
            $scope.showloading=false;
        });

        $scope.doRefresh = function() {
            TaskList.setOrderStatus($scope.status,0);
            $scope.$broadcast('scroll.refreshComplete');
        };
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

    })

    .controller('userCtrl', function($scope,$state,Storage,User,$rootScope,$ionicHistory,$stateParams,modifyInfo,Toast,modifyPassword) {

        var storageKey='user';
        console.log("localStorage"+Storage.get('user'));

        $scope.uid=$stateParams.uid;
        console.log($scope.uid);
        //每次加载前 判断是否登录
        $scope.$on('$ionicView.beforeEnter', function() {
            if(Storage.get(storageKey)&&Storage.get(storageKey).username!=''){
                $scope.userInfo=Storage.get(storageKey);
                console.log("userInfo"+$scope.userInfo);
            }else{
                $scope.userInfo='';
                $state.go('signin');  //路由跳转
            }
        });

        //退出登录
        $scope.logOut=function(){
            User.logout();
            $state.go('signin');  //路由跳转
        }

        //回退
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };


        $scope.jobType=[{name:'泥瓦',value:0,isCheck:false},{name:'涂料油漆',value:1,isCheck:false},{name:'蜘蛛人',value:2,isCheck:false},{name:'木工',value:3,isCheck:false},{name:'木作',value:4,isCheck:false},{name:'铁艺油漆',value:5,isCheck:false},
          {name:'粘贴壁纸',value:6,isCheck:false},{name:'石材修补',value:7,isCheck:false},{name:'电工',value:8,isCheck:false},{name:'管道工',value:9,isCheck:false},{name:'锁匠',value:10,isCheck:false},{name:'门窗制安',value:11,isCheck:false},{name:'收纳安装',value:12,isCheck:false},{name:'杂工',value:13,isCheck:false}]
        if(Storage.get(storageKey).goodAtWork!=null){
          var goodAtWork=Storage.get(storageKey).goodAtWork.split(',');//将擅长工种转化为数组

          goodAtWork.forEach(function(item1,index){
            $scope.jobType.forEach(function(item2,index){
              if(item1==item2.name){
                item2.isCheck=true
              }
            })
          })

        }

        //修改工种
        $scope.modifyJobType=function(){
          var goodAtWork='';
          $scope.jobType.forEach(function(item,index){
            if(item.isCheck==true){
              goodAtWork+=item.name+",";
            }
          })
          goodAtWork=goodAtWork.substr(0,goodAtWork.length-1);

          modifyInfo.modifyJobType(goodAtWork);
        }

        $scope.password={};

        //修改密码
        $scope.modifyPassword=function(){
           if($scope.password.oldPassword==undefined){
             Toast.show("请输入当前密码！");
           }
           else if($scope.password.newPassword==undefined){
             Toast.show("请输入新密码！");
           }
           else if($scope.password.newPassword!=$scope.password.newPassword2){
             Toast.show("新密码两次输入不一致！");
           }
           else{
             modifyPassword.sendModify($scope.password.oldPassword,$scope.password.newPassword);
           }

        }






    })

    //用户登录
    .controller('loginCtrl', function($scope,$state,$ionicLoading,User,Storage,$rootScope,$ionicHistory,CheckLogin) {

        console.log("打开app");

        //判断session是否已经失效
        $scope.checkLogin=function(){
            console.log("发送验证session的请求");
            CheckLogin.checkLogin(Storage.get("sessionId"));
        };
        $scope.checkLogin();

        $rootScope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };
        var storageKey='user';
        // $scope.$on('$ionicView.beforeEnter', function() {
        //     console.log("试图加载前运行：");
        //     if(Storage.get(storageKey)&&Storage.get(storageKey).username!=''&&Storage.get("sessionId")!=''){
        //         $scope.checkLogin();
        //     }
        //
        // });
    //检验请求发送成功后
        $scope.$on('User.CheckLoginUpdated', function() {
            console.log("检测session的结果："+CheckLogin.getResult().msg);
            if(CheckLogin.getResult().success){
                console.log("新的sessionId"+CheckLogin.getResult().newSessionId);
                Storage.set("sessionId",CheckLogin.getResult().newSessionId);
                $state.go('tab.user');  //路由跳转
            }
            // else{
            //     $state.go('signin');  //路由跳转
            // }
        })



        var storageKey='user';
    //一定要注意定义 我们的ng-model的对象 数据
        $scope.user={
            loginName:'',
            password:''
        }

        //用户登录
        $scope.signIn=function(){
            console.log($scope.user);
            User.login($scope.user.loginName,$scope.user.password);

        }
        //登录后
        $scope.$on('User.loginUpdated', function() {
            var userRel = User.getCurrentUser();
            console.log("userRel"+userRel);
            if(userRel.success==false||userRel==undefined){//登陆失败
                //    alert(userRel.message);
                $ionicLoading.show({
                    noBackdrop: true,
                    template: userRel.msg,
                    duration: 1500
                });
            }else{
                console.log("用户的sessonId："+userRel.sessionId);
                Storage.set(storageKey,userRel.currentUser);
                Storage.set("sessionId",userRel.sessionId);
                $state.go('tab.user');  //路由跳转

            }

        });

        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };

    })
    //我的维修记录
    .controller('repairRecordCtrl', function($scope,$rootScope,TaskList,$ionicHistory) {

        $scope.showloading=true;

        $scope.icon_arrow={mark_left:true,mark_right:true,value_left:'ion-arrow-down-b',value_right:'ion-arrow-down-b',font_color_left:'',font_color_left:'',
            is_show_left:false,is_show_right:false};
        $scope.timeValue='时间排序';
        $scope.statusValue='状态';
        $scope.status=0;
        $scope.flag=0;
        $scope.choseSelect=function(i){
            console.log('timeValue'+$scope.timeValue);
            if(i==2){
                $scope.icon_arrow.mark_left=!$scope.icon_arrow.mark_left;
                if($scope.icon_arrow.mark_left){          //左边关闭
                    $scope.icon_arrow.value_left='ion-arrow-down-b';
                    $scope.font_color_left='';
                    $scope.icon_arrow.is_show_left=false;
                }
                else{
                    $scope.icon_arrow.value_left='ion-arrow-up-b';
                    $scope.font_color_left='font_color_left';
                    $scope.icon_arrow.value_right='ion-arrow-down-b';
                    $scope.font_color_right='';
                    $scope.icon_arrow.is_show_right=false;
                    $scope.icon_arrow.mark_right=true;
                    $scope.icon_arrow.is_show_left=true;
                }
            }
            else{
                $scope.icon_arrow.mark_right=!$scope.icon_arrow.mark_right;
                if($scope.icon_arrow.mark_right){          //右边关闭
                    $scope.icon_arrow.value_right='ion-arrow-down-b';
                    $scope.font_color_right='';
                    $scope.icon_arrow.is_show_right=false;
                }
                else{
                    $scope.icon_arrow.value_right='ion-arrow-up-b';
                    $scope.font_color_right='font_color_right';
                    $scope.icon_arrow.value_left='ion-arrow-down-b';
                    $scope.font_color_left='';
                    $scope.icon_arrow.is_show_right=true;
                    $scope.icon_arrow.mark_left=true;
                    $scope.icon_arrow.is_show_left=false;
                }
            }
        }
        $scope.hideModalLeft=function(){
            $scope.icon_arrow.is_show_left=false;
        }
        $scope.hideModalRight=function(){
            $scope.icon_arrow.is_show_right=false;
        }

        $scope.$watch('timeValue',function(newValue,oldValue, scope){

            if (newValue !=oldValue) {
                $scope.icon_arrow.is_show_left=false;
                $scope.icon_arrow.value_left='ion-arrow-down-b';
                $scope.font_color_left='';
                $scope.icon_arrow.mark_left=true;


            }
            if( $scope.timeValue=='时间升序'){
                $scope.flag=1;
            }
            else if($scope.timeValue=='时间降序'){
                $scope.flag=0;
            }

            TaskList.setOrderStatus($scope.status, $scope.flag);


        });

        $scope.$watch('statusValue',function(newValue,oldValue, scope){

            if (newValue !=oldValue) {
                $scope.icon_arrow.is_show_right=false;
                $scope.icon_arrow.value_right='ion-arrow-down-b';
                $scope.font_color_right='';
                $scope.icon_arrow.mark_right=true;
            }

            if( $scope.statusValue=='已完成'){
                $scope.status=2;

            }
            else if( $scope.statusValue=='进行中'){
                $scope.status=1;
            }
            else if( $scope.statusValue=='异常件'){
                $scope.status=4;
            }
            else if( $scope.statusValue=='已转单'){
                $scope.status=3;
            }
            else if( $scope.statusValue=='待联系'){
                $scope.status=0;
            }

            TaskList.setOrderStatus($scope.status, $scope.flag);

        });

        $scope.$on('TaskList.listUpdated', function() {

            console.log("检测到更新完毕");
            $scope.taskListData = TaskList.getList();
            $scope.listNum=TaskList.getListNum();
            console.log("$scope.taskListData:"+$scope.taskListData);
            $scope.showloading=false;
        });

        $scope.doRefresh = function() {
            TaskList.setOrderStatus($scope.status, $scope.flag);
            $scope.$broadcast('scroll.refreshComplete');
        };

        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };







    })

    .controller('tabCtrl',function($scope,queryNum){
        console.log("tabCtrl");
        $scope.todoNum=0;
        $scope.taskNum=0;
      queryNum.query();
      $scope.$on('queryNum.Success', function() {
        $scope.todoNum=queryNum.getTodoNum();

      })
      $scope.openWeb=function() {
        cordova.ThemeableBrowser.open('http://112.74.165.39/dokuwiki/doku.php', '_blank', {
          statusbar: {
            color: '#444444'
          },
          toolbar: {
            height: 44,
            color: '#444444'
          },
          title: {
            color: '#ffffff',
            staticText: '知识库',
            showPageTitle: false
          },
          backButton: {
            wwwImage: 'img/back.png',
            wwwImagePressed: 'back_pressed',
            align: 'left',
            event: 'backPressed'
          },
          // customButtons: [
          //   {
          //     image: 'share',
          //     imagePressed: 'share_pressed',
          //     align: 'right',
          //     event: 'sharePressed'
          //   }
          // ],
          // menu: {
          //   image: 'menu',
          //   imagePressed: 'menu_pressed',
          //   title: 'Test',
          //   cancel: 'Cancel',
          //   align: 'right',
          //   items: [
          //     {
          //       event: 'helloPressed',
          //       label: 'Hello World!'
          //     },
          //     {
          //       event: 'testPressed',
          //       label: 'Test!'
          //     }
          //   ]
          // },
          backButtonCanClose: true
        }).addEventListener('backPressed', function (e) {
          // alert('back pressed');
        }).addEventListener('helloPressed', function (e) {
          alert('hello pressed');
        }).addEventListener('sharePressed', function (e) {
          alert(e.url);
        }).addEventListener(cordova.ThemeableBrowser.EVT_ERR, function (e) {
          console.error(e.message);
        }).addEventListener(cordova.ThemeableBrowser.EVT_WRN, function (e) {
          console.log(e.message);
        });
      }


    })
    .controller('nodeReportCtrl',function($scope,$stateParams,$ionicModal,$cordovaImagePicker,$timeout,$ionicHistory,$ionicActionSheet,Toast,FileUtil,SubmitNodeReport,$rootScope,Load){
        $scope.orderNum=$stateParams.aid;
        $scope.repairOrder={};
        $scope.repairOrder.repairStageContent='';
        // console.log("上传检修点报告："+aid);
        $scope.imgList=[];


        //  "添加附件"Event  
        $scope.addAttachment = function() {
            nonePopover();
            $ionicActionSheet.show({
                buttons: [
                    { text: '相机' },
                    { text: '图库' }
                ],
                cancelText: '关闭',
                cancel: function() {
                    return true;
                },
                buttonClicked: function(index) {

                    switch (index){

                        case 0:
                            appendByCamera();
                            break;
                        case 1:
                            pickImage();
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
        }
        //image picker  
        $scope.pickImage=function () {
            var options = {
                maximumImagesCount: 4,
                width: 800,
                height: 800,
                quality: 80
            };

            $cordovaImagePicker.getPictures(options)
                .then(function (results) {
                      if(results.length+$scope.imgList.length>4){
                        Toast.show("最多上传4张照片！");
                      }else {
                        for(var i=0;i<results.length;i++){
                          $scope.imgList.unshift(results[i]);
                        }
                      }
                }, function (error) {
                    // error getting photos  
                });

        }
      //上传照片
        $scope.submitNode=function(){
        if($scope.repairOrder.repairStageContent==''){
          Toast.show('请填写节点报告');

        }
        else if($scope.imgList.length==0){
          Toast.show('请选择照片上传');
        }
        else{

            for(var i=0;i< $scope.imgList.length;i++){
              Load.loading("正在提交...");
              FileUtil.upload( $scope.imgList[i]).then(function (response) {

              },function (err) {
                $ionicLoading.hide();
                Toast.show("结果:"+err);
              });
            }
        }

      }


      //监听上传成功后
      $scope.$on('RepairOrder.UploadSuccess', function() {
          if(FileUtil.getImgSrc().length==$scope.imgList.length){
            SubmitNodeReport.submit($scope.orderNum, $scope.repairOrder.repairStageContent,FileUtil.getImgSrc().toString());
          }

      })
      //监听节点报告提交成功
      $scope.$on('RepairOrder.NodeReportEd', function() {
          FileUtil.setImgSrc(); //上传成功后清空数组
          Toast.show("提交成功！");
          $timeout(function () {
            $ionicHistory.goBack();
          }, 1700);



      })
      //删除选中图片


      // $scope.deletePic=function () {
      //   console.log($scope.modal.index);
      //   $scope.imgList=$scope.imgList.slice($scope.modal.index);
      //   $scope.modal.hide();
      // }

      $ionicModal.fromTemplateUrl('modal.html', function (modal) {
        $scope.modal = modal;
        $scope.modal.deletePic=function () {
          console.log($scope.modal.index);
          $scope.imgList.splice($scope.modal.index,1);
          $scope.modal.hide();
        }
      }, {
        animation: 'slide-in-left',
        focusFirstInput: true
      });

      $scope.showBigPic=function(index){
        $scope.modal.src=$scope.imgList[index];
        $scope.modal.index=index;
        console.log(index);
        $scope.modal.show();

      }



})

    //选择收款项产品
    .controller('chooseProductCtrl', function($scope,$rootScope,productList,$ionicHistory,$state) {
         $scope.showloading=true;
        $scope.produceOne={};
        $scope.produceTwo={};
        $scope.produceThree={};
        $scope.produceOne.isShow=true;
        $scope.produceTwo.isShow=false;

        $scope.produceThree.isShow=false;

        $scope.produceOne.value=1;



        $scope.changeTab = function(index,productId) {
            $scope.status=status;
            var a=document.getElementById('sub_header_list').getElementsByTagName('a');
            for (var i = 0; i < 3; i++) {
                a[i].className = "button button-clear ";
            }
            a[index].className = "button button-clear sub_button_select";
            //console.log("produceOne："+$scope.produceOne.data);
            if(index==0){
                $scope.produceOne.isShow=true;
                $scope.produceTwo.isShow=false;
                $scope.produceThree.isShow=false;
                $scope.produceOne.value=productId;
                productList.setProductOne();

            }else if(index==1){
                $scope.produceOne.isShow=false;
                $scope.produceTwo.isShow=true;
                $scope.produceThree.isShow=false;
                $scope.produceTwo.value=productId;
                productList.setProductTwo(productId);
            }else{
                $scope.produceOne.isShow=false;
                $scope.produceTwo.isShow=false;
                $scope.produceThree.isShow=true;
                $scope.produceThree.value=productId;
                productList.setProductThree(productId);
            }

        };

        $scope.changeTab(0,0);
        $scope.$on('productList.listOneUpdated', function() {
            console.log("检测到更新完毕");
            $scope.produceOne.data = productList.getProductOne();
            console.log("$scope.taskListData:"+$scope.produceOne);
            $scope.showloading=false;
        });
        $scope.$on('productList.listTwoUpdated', function() {
            console.log("检测到更新完毕");
            $scope.produceTwo.data= productList.getProductTwo();
            //console.log("$scope.taskListData:"+$scope.taskListData);
            $scope.showloading=false;
        });
        $scope.$on('productList.listThreeUpdated', function() {
            console.log("检测到更新完毕");
            $scope.produceThree.data = productList.getProductThree();
            //console.log("$scope.taskListData:"+$scope.taskListData);
            $scope.showloading=false;
        });

        $scope.doRefresh = function() {
            TaskList.setOrderStatus($scope.status,0);
            $scope.$broadcast('scroll.refreshComplete');
        };
        $scope.back = function(){
            $ionicHistory.goBack();
            console.log("back");
        };


        //多选
        //创建变量用来保存选中结果
        $scope.selected = [];
        var updateSelected = function (action, id) {
            if (action == 'add' && $scope.selected.indexOf(id) == -1) $scope.selected.push(id);
            if (action == 'remove' && $scope.selected.indexOf(id) != -1) $scope.selected.splice($scope.selected.indexOf(id), 1);
        };
        //更新某一列数据的选择
        $scope.updateSelection = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateSelected(action, id);
        };
        //全选操作
        //$scope.selectAll = function ($event) {
        //    var checkbox = $event.target;
        //    var action = (checkbox.checked ? 'add' : 'remove');
        //    for (var i = 0; i < $scope.content.length; i++) {
        //        var contact = $scope.content[i];
        //        updateSelected(action, contact.id);
        //    }
        //};
        $scope.isSelected = function (id) {
            return $scope.selected.indexOf(id) >= 0;
        };
        //$scope.isSelectedAll = function () {
        //    return $scope.selected.length === $scope.content.length;
        //};

        $scope.summitProduct=function(){
            console.log("多选的结果为："+$scope.selected.join(","));
            $state.go("placeOrder",{productIds:$scope.selected.join(",")});
        }

    })

    //下单
    .controller('placeOrderCtrl', function($scope,$rootScope,placeOrder,$ionicHistory,$stateParams) {
        var productIds=$stateParams.productIds;
        $scope.productList={};
        placeOrder.getProductInfo(productIds);//URl获取参数
        $scope.productList=placeOrder.getProductInfo();



    })
